package com.yupi.oj.manager;

import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author FengHuan Wang
 * @Date 2025/3/13 8:09
 * @Version 1.0
 */
@Component
public class RedissonManager {

    @Resource
    private RedissonClient redissonClient;

    public void doLimite(String key){
        // 创建或获取限流器实例
        RRateLimiter rRateLimiter = redissonClient.getRateLimiter(key);
        // 设置限流规则：每秒钟最多一个许可，每个用户一个限流器
        rRateLimiter.trySetRate(RateType.PER_CLIENT, 1, 1, RateIntervalUnit.SECONDS);
        // 尝试获取许可，每当一个请求来了之后，请求一个令牌
        boolean tryAcquire = rRateLimiter.tryAcquire(1);
        if (!tryAcquire){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请求次数过多，请稍后再试");
        }
    }
}
